package com.sun.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class ExceptionallyExample {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("主线程开始");

        // 创建一个可能失败的任务
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务执行线程: " + Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException(e);
            }

            // 模拟50%的失败率
            if (Math.random() > 0.5) {
                throw new RuntimeException("任务执行失败");
            }

            return "任务执行成功";
        });

        // exceptionally: 异常处理，提供默认值
        CompletableFuture<String> handledFuture = future.exceptionally(ex -> {
            System.out.println("异常处理线程: " + Thread.currentThread().getName());
            System.err.println("捕获到异常: " + ex.getMessage());
            return "默认值（异常恢复）";
        });

        System.out.println("结果: " + handledFuture.get());
        System.out.println("主线程结束");
    }
}
